import Taro from '@tarojs/taro';
import { get as getGlobalData } from '../global_data'
import Api from './Api';

const BaseUrl = process.env['API_URL'];
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
function uploadImg() {
  return new Promise((resolve, reject) => {
    Taro.chooseImage({
      sourceType: ['camera'],
      count: 1
    }).then((d) => {
      let tempFiles = d.tempFiles[0];
      Taro.uploadFile({
        url: BaseUrl + Api['fileUpload'],
        filePath: tempFiles.path,
        name: 'file'
      }).then((res) => {
        let data = objparse(res.data);
        if (data) {
          resolve(BaseUrl + data.datas);
        } else {
          showtoast('上传图片出错')
          reject(null)
        }
      }).catch((e) => {
        console.log(e)
        showtoast('上传图片出错')
        reject(null)
      })
    })
  })
}
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
function objparse(obj, _object = '') {
  if (obj) {
    try {
      var obj = JSON.parse(obj)
    } catch (e) {
      return _object
    }
    return obj
  } else {
    return _object
  }
}
function oneDay(times) {
  var myDate = new Date(times);
  var week = myDate.getDay();
  switch (week) {
    case 0:
      return '周日';
    case 1:
      return '周一';
    case 2:
      return '周二';
    case 3:
      return '周三';
    case 4:
      return '周四';
    case 5:
      return '周五';
    case 6:
      return '周六';
  }
}
function getUserInfo() { //获取用户信息，暂时不用
  let getuserInfo = getGlobalData('userInfo');
  if (getuserInfo) {
    return getuserInfo;
  }
  try {
    var value = Taro.getStorageSync('userInfo') //暂定‘user_info’
    if (value) {
      try {
        var userInfo = JSON.parse(value);
      } catch (e) {
        return null
      }
      return userInfo;
    } else {
      return null;
    }
  } catch (e) {
    return null;
  }
}
function getWechatInfo() {
  try {
    var value = Taro.getStorageSync('weChatInfo');
    if (value) {
      try {
        var weChatInfo = JSON.parse(value);
      } catch (e) {
        return null
      }
      return weChatInfo;
    } else {
      return null;
    }
  } catch (e) {
    return null;
  }
}
function showLoading(text) { //showLoading简单封装
  Taro.showLoading({
    title: text || '加载中',
    mask: true,
  })
}

function hideLoading() { //隐藏Loading
  Taro.hideLoading()
}

function showtoast(val, icon, duration, mask) { //toast封装
  if (val) {
    Taro.showToast({
      title: val,
      icon: icon || 'none',
      duration: duration || 2000,
      mask: mask || false
    })
  }
}

function showModal(content) { //警示框
  Taro.showModal({
    title: '张中医急救',
    content: content,
    showCancel: false,
  })
}

var queryconcat = function (obj) { //url拼接参数
  if (typeof obj == "object") {
    var keys = Object.keys(obj);
    var results = [];
    for (var i = 0; i < keys.length; i++) {
      var keyName = keys[i];
      results.push(`${keyName}=${obj[keyName]}`);
    }
    return results.join("&");
  }
  return 'test=undefined'
}

var format = function (dateObj, fmt) { //时间格式转换
  var that = dateObj;
  var o = {
    "M+": that.getMonth() + 1, //月份
    "d+": that.getDate(), //日
    "h+": that.getHours(), //小时
    "m+": that.getMinutes(), //分
    "s+": that.getSeconds(), //秒
    "q+": Math.floor((that.getMonth() + 3) / 3), //季度
    "S": that.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (that.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}
Date.prototype.format = function (fmt) {
  format(this, fmt)
}

function splitK(num) { //金额千分符','
  var decimal = String(num).split('.')[1] || ''; //小数部分
  var tempArr = [];
  var revNumArr = String(num).split('.')[0].split("").reverse(); //倒序
  for (var i in revNumArr) {
    tempArr.push(revNumArr[i]);
    if ((i + 1) % 3 === 0 && i != revNumArr.length - 1) {
      tempArr.push(',');
    }
  }
  var zs = tempArr.reverse().join(''); //整数部分
  return decimal ? zs + '.' + decimal : zs;
}

/*
 * 将一个浮点数转成整数，返回整数和倍数。如 3.14 >> 314，倍数是 100
 * @param floatNum {number} 小数
 * @return {object}
 *   {times:100, num: 314}
 */
function isInteger(obj) { //是否为一个整数
  return Math.floor(obj) === obj
}
function toInteger(floatNum) {
  var ret = {
    times: 1,
    num: 0
  }
  if (isInteger(floatNum)) {
    ret.num = floatNum
    return ret
  }
  var strfi = floatNum + ''
  var dotPos = strfi.indexOf('.')
  var len = strfi.substr(dotPos + 1).length
  var times = Math.pow(10, len)
  var intNum = parseInt(floatNum * times + 0.5, 10)
  ret.times = times
  ret.num = intNum
  return ret
}

function operation(a, b, op) {
  var o1 = toInteger(a)
  var o2 = toInteger(b)
  var n1 = o1.num
  var n2 = o2.num
  var t1 = o1.times
  var t2 = o2.times
  var max = t1 > t2 ? t1 : t2
  var result = null
  switch (op) {
    case 'add':
      if (t1 === t2) { // 两个小数位数相同
        result = n1 + n2
      } else if (t1 > t2) { // o1 小数位 大于 o2
        result = n1 + n2 * (t1 / t2)
      } else { // o1 小数位 小于 o2
        result = n1 * (t2 / t1) + n2
      }
      return result / max
    case 'subtract':
      if (t1 === t2) {
        result = n1 - n2
      } else if (t1 > t2) {
        result = n1 - n2 * (t1 / t2)
      } else {
        result = n1 * (t2 / t1) - n2
      }
      return result / max
    case 'multiply':
      result = (n1 * n2) / (t1 * t2)
      return result
    case 'divide':
      result = (n1 / n2) * (t2 / t1)
      return result
  }
}

// 加减乘除的四个接口
function add(a, b) {
  return operation(a, b, 'add')
}

function subtract(a, b) {
  return operation(a, b, 'subtract')
}

function multiply(a, b) {
  return operation(a, b, 'multiply')
}

function divide(a, b) {
  return operation(a, b, 'divide')
}
/**
 * 修复精度错误的问题
 * @param num
 * @param s 精度
 * @returns {string}
 */
function toFixed(num, s) {
  var times = Math.pow(10, s)
  var des = num * times + 0.5
  des = parseInt(des, 10) / times
  return des + ''
}

function countdown(endtime) { //处理倒计时endtime需要毫秒//endtime=new Date(Time).getTime())自行转换
  var enddate = endtime;
  var date = enddate;
  if (date <= 0) {
    return null;
  }
  var days = date / 1000 / 60 / 60 / 24;
  var daysRound = Math.floor(days); //对一个数进行下舍入。
  var hours = date / 1000 / 60 / 60 - (24 * daysRound);
  var hoursRound = Math.floor(hours);
  var minutes = date / 1000 / 60 - (24 * 60 * daysRound) - (60 * hoursRound);
  var minutesRound = Math.floor(minutes);
  var seconds = date / 1000 - (24 * 60 * 60 * daysRound) - (60 * 60 * hoursRound) - (60 * minutesRound);
  var secondsRound = Math.floor(seconds);
  return [addZero(daysRound), addZero(hoursRound), addZero(minutesRound), addZero(secondsRound)];
}

function addZero(numbers) { //小于10前面加一个零
  if (numbers < 10) {
    return "0" + numbers
  }
  return numbers;
}
/**
 * 跳转页面
 * @param url {string}//打开页面的url
 * @param complete {function} //打开页面完成
 * @param {string,obecjet....}//传过来的参数
 * @param success{function}//成功打开页面回调
 * @param fail{function}//打开页面失败回调
 */
function toPage(url, complete, param = null, success, fail) { //跳转页面
  Taro.navigateTo({
    url: url,
    success: () => {
      success && success(param)
    },
    fail: () => {
      fail && fail(param)
    },
    complete: () => {
      complete && complete(param)
    }
  })
}
//手机号码验证封装
function validatemobile(mobile) {
  if (mobile.length == 0) {
    showtoast('请输入手机号！')
    return false;
  }
  if (mobile.length != 11) {
    showtoast('手机号长度有误！')
    return false;
  }
  var myreg = /^1[345678]\d{9}$/;
  if (!myreg.test(mobile)) {
    showtoast('手机号有误！')
    return false;
  }
  return true;
}
// 邮箱验证
function checkEmail(email) {
  let str = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/
  if (str.test(email)) {
    return true
  } else {

    showtoast('请填写正确的邮箱号')
    return false
  }
}

function onChage(obj, e) { //input的简单扩展
  var bindName = e.currentTarget.dataset.name;
  if (e.currentTarget.dataset.min) {
    if (parseInt(e.currentTarget.dataset.min) > parseInt(e.detail.value)) {
      e.detail.value = e.currentTarget.dataset.min
    }
  }
  if (e.currentTarget.dataset.max) {
    if (e.currentTarget.dataset.max < parseInt(e.detail.value)) {
      e.detail.value = e.currentTarget.dataset.max
    }
  }
  if (e.currentTarget.dataset.isNumber) {
    if (e.currentTarget.dataset.isNumber == "true" || e.currentTarget.dataset.isNumber == true) {
      e.detail.value = parseInt(e.detail.value)
    }
  }
  if (e.currentTarget.dataset.isFloat) {
    if (e.currentTarget.dataset.isFloat == "true" || e.currentTarget.dataset.isFloat == true) {
      var cPointCount = indexOfCount(e.detail.value, ".");
      var cPointIndex = e.detail.value.indexOf(".");
      if (!(cPointCount == 1 && cPointIndex == (e.detail.value.length - 1) && cPointIndex != -1)) {
        e.detail.value = parseFloat(e.detail.value)
      }
    }
  }
  obj.setData({
    [bindName]: e.detail.value
  });
}
function indexOfCount(data, indexStr) {
  if (indexStr == ".") {
    indexStr = "\\.";
  }
  if (indexStr == " ") {
    indexStr = "\\t";
  }
  indexStr = new RegExp(indexStr, "ig");
  return data.match(indexStr) ? data.match(indexStr).length : 0;
}

/**
 * 获取时间戳
 */
function getTimeStamp(time) {
  var newTime = time.replace(/\-/g, "/");
  var convertTime = Date.parse(new Date(newTime));
  console.log(time + "的时间戳为：" + convertTime);
  return convertTime;
}
export default {
  formatTime: formatTime,
  getUserInfo: getUserInfo,
  getWechatInfo: getWechatInfo,
  showLoading: showLoading,
  hideLoading: hideLoading,
  showtoast: showtoast,
  showModal: showModal,
  queryconcat: queryconcat,
  format: format,
  countdown: countdown,
  splitK: splitK,
  toFixed: toFixed,
  add: add,
  subtract: subtract,
  multiply: multiply,
  divide: divide,
  toPage: toPage,
  validatemobile: validatemobile,
  checkEmail: checkEmail,
  getTimeStamp,
  onChage,
  objparse,
  oneDay,
  addZero,
  uploadImg
}